// pages/appointment/add.js
// 引入相关服务
const petService = require('../../services/pet');
const departmentService = require('../../services/department');
const hospitalService = require('../../services/hospital');
const appointmentService = require('../../services/appointment');
const util = require('../../utils/util');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    petId: '', // 从页面参数获取的宠物ID
    pets: [], // 宠物列表
    departments: [], // 科室列表
    doctors: [], // 医生列表
    appointmentTypes: ['普通就诊', '疫苗接种', '绝育手术', '其他'],
    timeSlots: [
      '09:00-09:30', '09:30-10:00', '10:00-10:30', '10:30-11:00', '11:00-11:30', '11:30-12:00',
      '14:00-14:30', '14:30-15:00', '15:00-15:30', '15:30-16:00', '16:00-16:30', '16:30-17:00',
      '17:00-17:30', '17:30-18:00'
    ],
    formData: {
      petId: '',
      departmentId: '',
      staffId: '',
      type: 0,
      appointmentDate: '',
      appointmentTime: '',
      description: '',
      remark: ''
    },
    selectedPetIndex: 0,
    selectedDepartmentIndex: 0,
    selectedDoctorIndex: 0,
    selectedTypeIndex: 0,
    selectedTimeIndex: 0,
    minDate: '',
    maxDate: '',
    isSubmitting: false,
    loading: {
      pets: true,
      departments: true,
      doctors: false
    },
    showPayPopup: false,  // 是否显示支付弹窗
    tempAppointmentId: '', // 临时存储预约ID
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    // 显示加载中
    wx.showLoading({
      title: '加载中...',
      mask: true
    });
    
    // 设置日期范围（今天到30天后）
    const today = new Date();
    const maxDate = new Date();
    maxDate.setDate(today.getDate() + 30);
    
    const formatDate = date => {
      const year = date.getFullYear();
      const month = (date.getMonth() + 1).toString().padStart(2, '0');
      const day = date.getDate().toString().padStart(2, '0');
      return `${year}-${month}-${day}`;
    };
    
    this.setData({
      minDate: formatDate(today),
      maxDate: formatDate(maxDate),
      'formData.appointmentDate': formatDate(today)
    });
    
    // 如果有传入宠物ID，则设置
    if (options.petId) {
      this.setData({
        petId: options.petId,
        'formData.petId': options.petId
      });
    }
    
    // 加载数据
    Promise.all([
      this.loadPets(),
      this.loadDepartments()
    ]).finally(() => {
      wx.hideLoading();
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    Promise.all([
      this.loadPets(),
      this.loadDepartments()
    ]).finally(() => {
      wx.stopPullDownRefresh();
    });
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    return {
      title: '宠物医院预约挂号',
      path: '/pages/appointment/add'
    };
  },

  /**
   * 加载宠物列表
   */
  loadPets() {
    this.setData({
      'loading.pets': true
    });
    
    return new Promise((resolve, reject) => {
      petService.getPetList()
        .then(res => {
          const pets = res.records || [];
          
          if (pets.length === 0) {
            wx.showModal({
              title: '提示',
              content: '您还没有添加宠物，是否现在添加?',
              confirmText: '去添加',
              success: (res) => {
                if (res.confirm) {
                  wx.navigateTo({
                    url: '/pages/pet/add'
                  });
                } else {
                  wx.navigateBack();
                }
              }
            });
            return;
          }
          
          this.setData({
            pets,
            'loading.pets': false
          });
          
          // 如果有传入的宠物ID，找到对应的索引
          if (this.data.petId && pets.length > 0) {
            const index = pets.findIndex(pet => pet.id.toString() === this.data.petId.toString());
            if (index !== -1) {
              this.setData({
                selectedPetIndex: index,
                'formData.petId': pets[index].id
              });
            } else {
              // 默认选择第一个宠物
              this.setData({
                'formData.petId': pets[0].id,
                selectedPetIndex: 0
              });
            }
          } else if (pets.length > 0) {
            // 默认选择第一个宠物
            this.setData({
              'formData.petId': pets[0].id,
              selectedPetIndex: 0
            });
          }
          
          resolve(pets);
        })
        .catch(err => {
          console.error('获取宠物列表失败', err);
          this.setData({
            'loading.pets': false
          });
          
          wx.showToast({
            title: '获取宠物列表失败',
            icon: 'none'
          });
          
          reject(err);
        });
    });
  },

  /**
   * 加载科室列表
   */
  loadDepartments() {
    this.setData({
      'loading.departments': true
    });
    
    return new Promise((resolve, reject) => {
      departmentService.getDepartmentList()
        .then(res => {
          const departments = res.records || [];
          
          this.setData({
            departments,
            'loading.departments': false
          });
          
          if (departments.length > 0) {
            this.setData({
              'formData.departmentId': departments[0].id,
              selectedDepartmentIndex: 0
            });
            
            // 加载该科室下的医生
            this.loadDoctors(departments[0].id);
          }
          
          resolve(departments);
        })
        .catch(err => {
          console.error('获取科室列表失败', err);
          this.setData({
            'loading.departments': false
          });
          
          wx.showToast({
            title: '获取科室列表失败',
            icon: 'none'
          });
          
          reject(err);
        });
    });
  },

  /**
   * 加载医生列表
   */
  loadDoctors(departmentId) {
    if (!departmentId) {
      console.warn('无科室ID，无法加载医生列表');
      return Promise.resolve([]);
    }
    
    this.setData({
      'loading.doctors': true,
      doctors: []
    });
    
    return new Promise((resolve, reject) => {
      hospitalService.getStaffList(departmentId)
        .then(res => {
          const doctors = res.records || [];
          
          this.setData({
            doctors,
            'loading.doctors': false
          });
          
          if (doctors.length > 0) {
            this.setData({
              'formData.staffId': doctors[0].id,
              selectedDoctorIndex: 0
            });
          } else {
            this.setData({
              'formData.staffId': ''
            });
            
            wx.showToast({
              title: '该科室暂无医生',
              icon: 'none'
            });
          }
          
          resolve(doctors);
        })
        .catch(err => {
          console.error('获取医生列表失败', err);
          this.setData({
            'loading.doctors': false
          });
          
          wx.showToast({
            title: '获取医生列表失败',
            icon: 'none'
          });
          
          reject(err);
        });
    });
  },

  /**
   * 宠物选择器变化
   */
  bindPetChange(e) {
    const index = parseInt(e.detail.value);
    if (isNaN(index) || index < 0 || index >= this.data.pets.length) {
      console.warn('无效的宠物索引:', index);
      return;
    }
    
    this.setData({
      selectedPetIndex: index,
      'formData.petId': this.data.pets[index].id
    });
    
    console.log('已选择宠物:', this.data.pets[index].name);
  },

  /**
   * 科室选择器变化
   */
  bindDepartmentChange(e) {
    const index = parseInt(e.detail.value);
    if (isNaN(index) || index < 0 || index >= this.data.departments.length) {
      console.warn('无效的科室索引:', index);
      return;
    }
    
    this.setData({
      selectedDepartmentIndex: index,
      'formData.departmentId': this.data.departments[index].id,
      selectedDoctorIndex: 0,
      'formData.staffId': ''
    });
    
    console.log('已选择科室:', this.data.departments[index].name);
    
    // 加载该科室下的医生
    this.loadDoctors(this.data.departments[index].id);
  },

  /**
   * 医生选择器变化
   */
  bindDoctorChange(e) {
    const index = parseInt(e.detail.value);
    if (isNaN(index) || index < 0 || index >= this.data.doctors.length) {
      console.warn('无效的医生索引:', index);
      return;
    }
    
    this.setData({
      selectedDoctorIndex: index,
      'formData.staffId': this.data.doctors[index].id
    });
    
    console.log('已选择医生:', this.data.doctors[index].name);
  },

  /**
   * 预约类型选择器变化
   */
  bindTypeChange(e) {
    const index = parseInt(e.detail.value);
    if (isNaN(index) || index < 0 || index >= this.data.appointmentTypes.length) {
      console.warn('无效的预约类型索引:', index);
      return;
    }
    
    this.setData({
      selectedTypeIndex: index,
      'formData.type': index
    });
    
    console.log('已选择预约类型:', this.data.appointmentTypes[index]);
  },

  /**
   * 日期选择器变化
   */
  bindDateChange(e) {
    this.setData({
      'formData.appointmentDate': e.detail.value
    });
    
    console.log('已选择预约日期:', e.detail.value);
  },

  /**
   * 时间段选择器变化
   */
  bindTimeChange(e) {
    const index = parseInt(e.detail.value);
    if (isNaN(index) || index < 0 || index >= this.data.timeSlots.length) {
      console.warn('无效的时间段索引:', index);
      return;
    }
    
    this.setData({
      selectedTimeIndex: index,
      'formData.appointmentTime': this.data.timeSlots[index]
    });
    
    console.log('已选择预约时间段:', this.data.timeSlots[index]);
  },

  /**
   * 输入描述
   */
  inputDescription(e) {
    this.setData({
      'formData.description': e.detail.value
    });
  },

  /**
   * 输入备注
   */
  inputRemark(e) {
    this.setData({
      'formData.remark': e.detail.value
    });
  },

  /**
   * 提交预约
   */
  submitAppointment(e) {
    // 防止重复提交
    if (this.data.isSubmitting) {
      return;
    }
    
    this.setData({
      isSubmitting: true
    });
    
    // 表单验证
    if (!this.data.formData.petId) {
      wx.showToast({
        title: '请选择宠物',
        icon: 'none'
      });
      this.setData({ isSubmitting: false });
      return;
    }
    
    if (!this.data.formData.departmentId) {
      wx.showToast({
        title: '请选择科室',
        icon: 'none'
      });
      this.setData({ isSubmitting: false });
      return;
    }
    
    if (!this.data.formData.staffId) {
      wx.showToast({
        title: '请选择医生',
        icon: 'none'
      });
      this.setData({ isSubmitting: false });
      return;
    }
    
    if (this.data.formData.type === undefined || this.data.formData.type === null) {
      this.setData({
        'formData.type': 0,
        selectedTypeIndex: 0
      });
    }
    
    if (!this.data.formData.appointmentDate) {
      wx.showToast({
        title: '请选择预约日期',
        icon: 'none'
      });
      this.setData({ isSubmitting: false });
      return;
    }
    
    if (!this.data.formData.appointmentTime) {
      wx.showToast({
        title: '请选择预约时间段',
        icon: 'none'
      });
      this.setData({ isSubmitting: false });
      return;
    }
    
    // 获取表单中输入的描述和备注
    const formValues = e.detail.value;
    const description = formValues.description || this.data.formData.description;
    const remark = formValues.remark || this.data.formData.remark;
    
    if (!description || description.trim() === '') {
      wx.showToast({
        title: '请输入症状描述',
        icon: 'none'
      });
      this.setData({ isSubmitting: false });
      return;
    }
    
    // 构造完整的日期时间
    const [startTime] = this.data.formData.appointmentTime.split('-');
    const appointmentTime = `${this.data.formData.appointmentDate} ${startTime}:00`;
    
    // 构造请求数据
    const appointmentData = {
      petId: this.data.formData.petId,
      staffId: this.data.formData.staffId,
      departmentId: this.data.formData.departmentId,
      type: this.data.formData.type,
      appointmentTime: appointmentTime,
      description: description,
      remark: remark
    };
    
    console.log('提交预约数据:', appointmentData);
    
    wx.showLoading({
      title: '提交中...',
      mask: true
    });
    
    appointmentService.createAppointment(appointmentData)
      .then(res => {
        wx.hideLoading();
        
        // 显示支付弹窗
        this.setData({
          tempAppointmentId: res,
          showPayPopup: true
        });
      })
      .catch(err => {
        console.error('创建预约失败', err);
        wx.hideLoading();
        
        wx.showToast({
          title: err.message || '预约失败，请重试',
          icon: 'none'
        });
      })
      .finally(() => {
        this.setData({
          isSubmitting: false
        });
      });
  },

  /**
   * 关闭支付弹窗
   */
  closePayPopup() {
    this.setData({
      showPayPopup: false
    });
    // 取消预约
    if (this.data.tempAppointmentId) {
      appointmentService.cancelAppointment(this.data.tempAppointmentId)
        .then(() => {
          console.log('取消预约成功');
          wx.showToast({
            title: '已取消预约',
            icon: 'none'
          });
        })
        .catch(err => {
          console.error('取消预约失败', err);
        });
    }
  },

  /**
   * 确认支付
   */
  confirmPay() {
    // 这里模拟支付成功
    wx.showLoading({
      title: '支付中...',
      mask: true
    });

    setTimeout(() => {
      wx.hideLoading();
      this.setData({
        showPayPopup: false
      });
      
      wx.showToast({
        title: '支付成功',
        icon: 'success',
        duration: 2000
      });

      // 支付成功后跳转到预约详情页
      setTimeout(() => {
        wx.redirectTo({
          url: `/pages/appointment/detail?id=${this.data.tempAppointmentId}`
        });
      }, 2000);
    }, 1500);
  }
})